package com.travel.interceptor;

import com.travel.common.UserContext;
import com.travel.entity.po.User;
import com.travel.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户上下文拦截器
 * 负责从请求中提取用户信息并设置到UserContext中
 */
@Slf4j
public class UserContextInterceptor implements HandlerInterceptor {

    private static final String AUTH_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 如果是OPTIONS则结束请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(HttpStatus.NO_CONTENT.value());
            return false;
        }

        try {
            log.debug("开始处理请求: {}", request.getRequestURI());
            
            // 从请求头获取token
            String authHeader = request.getHeader(AUTH_HEADER);
            if (StringUtils.hasText(authHeader) && authHeader.startsWith(BEARER_PREFIX)) {
                String token = authHeader.substring(BEARER_PREFIX.length());
                log.debug("从请求头中获取到token: {}", token.substring(0, Math.min(token.length(), 20)) + "...");
                
                if (JWTUtil.validateToken(token)) {
                    log.debug("token验证成功");
                    User user = JWTUtil.getUser(token);
                    
                    if (user != null) {
                        // 设置用户上下文
                        UserContext.set(user.getId(), user.getPreferredLanguage(), user.getUsername());
                        log.debug("设置用户上下文成功, userId: {}, preferredLanguage: {}", 
                                user.getId(), user.getPreferredLanguage());
                    } else {
                        log.warn("从token中获取的用户信息为空");
                    }
                } else {
                    log.warn("token验证失败");
                }
            } else {
                log.debug("请求头中未找到有效的Authorization信息");
            }
        } catch (Exception e) {
            log.error("设置用户上下文失败: {}", e.getMessage(), e);
            // 即使提取失败，也允许请求继续处理
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
                               Object handler, Exception ex) {
        // 清除用户上下文，防止内存泄漏
        Long userId = UserContext.getUserId();
        String preferredLanguage = UserContext.getPreferredLanguage();
        
        UserContext.clear();
        
        log.debug("请求完成，已清除用户上下文, userId: {}, preferredLanguage: {}", 
                userId, preferredLanguage);
    }
} 